//
//  LSDisasterGoodsStorageStatusInfoSearchViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/27.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "LSDisasterGoodsStorageStatusInfoSearchViewController.h"
#import "LSInfoSearchTableViewCell.h"

#define headerSearchViewHeight 53
#define CountPerPage 10

@interface LSDisasterGoodsStorageStatusInfoSearchViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *disasterGoodsStorageStatusInfoTableView;
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, assign) int tableViewPage;
@property (nonatomic, assign) BOOL textFieldShouldBeginEditing;
@property (nonatomic, strong) NSMutableArray <NSDictionary *> *dataArrayM;
@property (nonatomic, strong) NSArray *storageArr;
@property (nonatomic, copy) NSString *orgid;
@property (nonatomic, copy) NSString *repid;
@property (nonatomic, strong) NZKNoDataView *nodataView;
@property (nonatomic, strong) NZKNetworkErrorView *networkErrorView;
@end

static NSString *LSInfoSearchTableViewCellID = @"LSInfoSearchTableViewCellID";

@implementation LSDisasterGoodsStorageStatusInfoSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"救灾物资储备情况查询";
    self.textFieldShouldBeginEditing = false;
    self.orgid = @"";
    self.repid = @"";
    [self setUpHeaderSearchView];
    [self loadStorageOfMaterialsForDisaster];
    [self.view addSubview:self.disasterGoodsStorageStatusInfoTableView];
    _disasterGoodsStorageStatusInfoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadStorageOfMaterialsForDisaster)];
}

- (void)setUpHeaderSearchView {
    UIView *headerSearchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, headerSearchViewHeight)];
    headerSearchView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:headerSearchView];
    UIView *headerViewBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight-0.5, ScreenWidth, 0.5)];
    headerViewBottomLineView.backgroundColor = hexColor(CCCCCC);
    [headerSearchView addSubview:headerViewBottomLineView];
    
    // 姓名输入框
    UITextField *nameTF = [[UITextField alloc] initWithFrame:CGRectMake(15, 5+4, ScreenWidth-30-15, 36)];
    self.nameTF = nameTF;
    nameTF.delegate = self;
    nameTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
    nameTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    nameTF.layer.borderWidth = 1;
    nameTF.returnKeyType = UIReturnKeySearch;
    nameTF.placeholder = @"请输入物资或仓库名称";
    nameTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
    nameTF.leftViewMode = UITextFieldViewModeAlways;
    [headerSearchView addSubview:nameTF];
    
//    UITextField *cardNumberTF = [[UITextField alloc] initWithFrame:CGRectMake(15+(ScreenWidth-100)/2+10, 5+4, (ScreenWidth-100)/2, 36)];
//    cardNumberTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
//    cardNumberTF.layer.borderColor = hexColor(dbdbdb).CGColor;
//    cardNumberTF.layer.borderWidth = 1;
//    cardNumberTF.returnKeyType = UIReturnKeySearch;
//    cardNumberTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
//    cardNumberTF.placeholder = @"请输入仓库名称";
//    cardNumberTF.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 1)];
//    cardNumberTF.leftViewMode = UITextFieldViewModeAlways;
//    [headerSearchView addSubview:cardNumberTF];
    
//    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-15-50, 5+4, 50, 36)];
//    searchButton.layer.cornerRadius = 4;
//    searchButton.layer.masksToBounds = true;
//    searchButton.backgroundColor = NAV_COLOR;
//    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
//    searchButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:12];
//    [searchButton addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];
//    [headerSearchView addSubview:searchButton];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (self.textFieldShouldBeginEditing) {
        [self showSelectControllerForTextField:textField WithContentArray:self.storageArr];
    }
    return false;
}

- (void)showSelectControllerForTextField:(UITextField *)textField WithContentArray:(NSArray *)contentArray {
    MJWeakSelf
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (int i = 0; i < contentArray.count; i++) {
        NSDictionary *dict = contentArray[i];
        if (dict && dict.count > 0) {
            if (![[ValidateUtils validateNull:dict[@"repository_name"]] isEqualToString:@""]) {
                [alertC addActionTarget:alertC title:dict[@"repository_name"] color:NAV_COLOR action:^(UIAlertAction *action) {
                    textField.text = dict[@"repository_name"];
                    weakSelf.orgid = [ValidateUtils validateNull:[UserInfoModel sharedInstance].departid];
                    weakSelf.repid = [ValidateUtils validateNull:dict[@"id"]];
                    [weakSelf loadData];
                }];
            }
        }
    }
    [alertC addCancelActionTarget:alertC color:NAV_COLOR title:@"取消"];
    [self presentViewController:alertC animated:true completion:nil];
}

- (void)loadStorageOfMaterialsForDisaster {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:StorageOfMaterialsForDisaster param:@{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token]} completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        [self.networkErrorView removeFromSuperview];
        [self.disasterGoodsStorageStatusInfoTableView addSubview:self.nodataView];
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray && dataArray.count > 0) {
                    self.nameTF.text = dataArray.firstObject[@"repository_name"];
                    self.textFieldShouldBeginEditing = true;
                    self.storageArr = dataArray;
                } else {
                    [self.networkErrorView removeFromSuperview];
                    [self.disasterGoodsStorageStatusInfoTableView addSubview:self.nodataView];
                }
            } else {
                [self.nodataView removeFromSuperview];
                [self.disasterGoodsStorageStatusInfoTableView addSubview:self.networkErrorView];
                self.networkErrorView.tipText = [ValidateUtils validateNull:responseObject[@"message"]];
            }
        } else {
            [self.nodataView removeFromSuperview];
            [self.disasterGoodsStorageStatusInfoTableView addSubview:self.networkErrorView];
            self.networkErrorView.tipText = [NSString stringWithFormat:@"%@",connectionError.localizedDescription];
        }
    }];
}

- (void)loadData {
    if ([self.nameTF.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请选择要查询的仓库"];
        return;
    }
    if ([self.orgid isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"数据源depid为空"];
        return;
    } else if ([self.repid isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"数据源repid为空"];
        return;
    } else {
        self.tableViewPage = 1;
        NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"orgid":self.orgid,@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"repid":self.repid,@"page":[NSString stringWithFormat:@"%d",self.tableViewPage]};
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
        [NetworkUtils requestNOHandleWithMethod:@"POST" URL:MaterialsForDisasterList param:param completionHandler:^(id responseObject, NSError *connectionError) {
            [hud hideAnimated:true];
            self.disasterGoodsStorageStatusInfoTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
            [self.disasterGoodsStorageStatusInfoTableView.mj_header endRefreshing];
            if (!connectionError) {
                NSNumber *status = [responseObject objectForKey:@"status"];
                if (status.integerValue == 200) {
                    NSArray *dataArray = [responseObject objectForKey:@"data"];
                    if (dataArray && dataArray.count > 0) {
                        [self.nodataView removeFromSuperview];
                        [self.networkErrorView removeFromSuperview];
                        self.dataArrayM = dataArray.mutableCopy;
                        if (self.dataArrayM.count < self.tableViewPage*CountPerPage) {
                            [self.disasterGoodsStorageStatusInfoTableView.mj_footer endRefreshingWithNoMoreData];
                        }
                        [self.disasterGoodsStorageStatusInfoTableView reloadData];
                    } else {
                        [self.networkErrorView removeFromSuperview];
                        [self.disasterGoodsStorageStatusInfoTableView addSubview:self.nodataView];
                    }
                } else {
                    [self.nodataView removeFromSuperview];
                    [self.disasterGoodsStorageStatusInfoTableView addSubview:self.networkErrorView];
                    self.networkErrorView.tipText = [ValidateUtils validateNull:responseObject[@"message"]];
                }
            } else {
                [self.nodataView removeFromSuperview];
                [self.disasterGoodsStorageStatusInfoTableView addSubview:self.networkErrorView];
                self.networkErrorView.tipText = [NSString stringWithFormat:@"%@",connectionError.localizedDescription];
            }
        }];
    }
}

- (void)loadMoreData {
    if ([self.orgid isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"数据源depid为空"];
        return;
    } else if ([self.repid isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"数据源repid为空"];
        return;
    } else {
        self.tableViewPage++;
        NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"orgid":self.orgid,@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"repid":self.repid,@"page":[NSString stringWithFormat:@"%d",self.tableViewPage]};
        [NetworkUtils requestNOHandleWithMethod:@"POST" URL:MaterialsForDisasterList param:param completionHandler:^(id responseObject, NSError *connectionError) {
            if (!connectionError) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray && dataArray.count > 0) {
                    [self.dataArrayM addObjectsFromArray:dataArray];
                    if (self.dataArrayM.count < self.tableViewPage*CountPerPage) {
                        [self.disasterGoodsStorageStatusInfoTableView.mj_footer endRefreshingWithNoMoreData];
                    } else {
                        [self.disasterGoodsStorageStatusInfoTableView.mj_footer endRefreshing];
                    }
                    [self.disasterGoodsStorageStatusInfoTableView reloadData];
                } else {
                    self.tableViewPage--;
                    [self.disasterGoodsStorageStatusInfoTableView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                self.tableViewPage--;
                [self.disasterGoodsStorageStatusInfoTableView.mj_footer endRefreshing];
                [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
            }
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSInfoSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSInfoSearchTableViewCellID forIndexPath:indexPath];
    cell.rightArrowImageView.hidden = true;
    NSDictionary *dataDict = self.dataArrayM[indexPath.row];
    cell.subTitleLabel.textAlignment = NSTextAlignmentRight;
    NSMutableString *mainTitleLabelTextM = [[NSMutableString alloc] initWithString:[ValidateUtils validateNull:dataDict[@"wzmc"]]];
    if (![[ValidateUtils validateNull:dataDict[@"xh"]] isEqualToString:@""]) {
        [mainTitleLabelTextM appendFormat:@"（%@）",[ValidateUtils validateNull:dataDict[@"xh"]]];
    }
    cell.mainTitleLabel.text = mainTitleLabelTextM.copy;
    cell.subTitleLabel.text = [NSString stringWithFormat:@"剩余%d%@",[ValidateUtils validateNull:dataDict[@"kcl"]].intValue,[ValidateUtils validateNull:dataDict[@"dw"]]];
    cell.bottomLabel.text = [ValidateUtils validateNull:dataDict[@"ckmc"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSInfoSearchTableViewCellHeight;
}

- (UITableView *)disasterGoodsStorageStatusInfoTableView {
    if (!_disasterGoodsStorageStatusInfoTableView) {
        _disasterGoodsStorageStatusInfoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, headerSearchViewHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight - headerSearchViewHeight)];
        _disasterGoodsStorageStatusInfoTableView.backgroundColor = UIColor.whiteColor;
        _disasterGoodsStorageStatusInfoTableView.separatorInset = UIEdgeInsetsZero;
        _disasterGoodsStorageStatusInfoTableView.delegate = self;
        _disasterGoodsStorageStatusInfoTableView.dataSource = self;
        _disasterGoodsStorageStatusInfoTableView.tableFooterView = [UIView new];
        [_disasterGoodsStorageStatusInfoTableView registerClass:LSInfoSearchTableViewCell.class forCellReuseIdentifier:LSInfoSearchTableViewCellID];
    }
    return _disasterGoodsStorageStatusInfoTableView;
}

- (NSMutableArray <NSDictionary *> *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}

- (NSArray *)storageArr {
    if (!_storageArr) {
        _storageArr = [[NSArray alloc] init];
    }
    return _storageArr;
}

- (NZKNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[NZKNoDataView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight) withTip:@"暂无相关信息" andButtonText:nil];
    }
    return _nodataView;
}

- (NZKNetworkErrorView *)networkErrorView {
    if (!_networkErrorView) {
        WS
        _networkErrorView = [[NZKNetworkErrorView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSearchViewHeight) withRefreshBlock:^{
            [weakSelf loadData];
        }];
    }
    return _networkErrorView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
